//
//  UIContainer.m
//  storeapp
//
//  Created by huangyi on 13-3-18.
//  Copyright (c) 2013年 ios. All rights reserved.
//

#import "UIContainer.h"
#import "NSString+utils.h"
#import "UIView+utils.h"

#define defaultIdentifier "undefined"

@interface UIContainer () <UIScrollViewDelegate>

@property(nonatomic,strong)NSArray *arrRect;

@end

@implementation UIContainer

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [self initView];
    }
    return self;
}
-(id)initWithCoder:(NSCoder *)aDecoder{
    self=[super initWithCoder:aDecoder];
    if (self) {
        [self initView];
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

-(void)initView{
    self.delegate=self;
}

-(void)reloadView{
    NSCAssert(self.dataSource, @"UIContainer dataSource undefined");
    //dispatch_async(dispatch_get_main_queue(), ^{
        NSArray *subviews=self.subviews;
        int numofview=subviews.count;
        for (int i=0; i<numofview; i++) {
            UIView *v=subviews[i];
            NSString *uuid=v.uuid;
            if (uuid!=nil) {
                v.tag=-1;
                v.hidden=YES;
            }
        }
        int count=[self.dataSource numberOfViewInContainerView:self];
        CGSize contentSize=CGSizeZero;
        NSMutableArray *array=[NSMutableArray array];
        for (int i=0; i<count; i++) {
            CGRect rect=[self.dataSource containerView:self rectOfViewAtIndex:i];
            contentSize.width=MAX(contentSize.width, CGRectGetMaxX(rect));
            contentSize.height=MAX(contentSize.height, CGRectGetMaxY(rect));
            [array addObject:NSStringFromCGRect(rect)];
        }
        self.arrRect=array;
        [self loadVisibleView];
        self.contentSize=contentSize;
    //});
}

-(void)removeInvisibleView{
    CGRect vis=CGRectMake(self.contentOffset.x, self.contentOffset.y, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds));
    NSArray *subviews=self.subviews;
    int count=subviews.count;
    for (int i=0; i<count; i++) {
        UIView *v=subviews[i];
        CGRect rect=v.frame;
        if (!CGRectIntersectsRect(vis, rect)) {
            NSString *uuid=v.uuid;
            if (uuid!=nil) {
                [v removeFromSuperview];
            }
        }
    }
}

-(UIView*)reuseableViewWithIdentifier:(NSString*)str{
    if (str==nil) {
        str=NSStringFromCString(defaultIdentifier);
    }
    UIView *view=nil;
    CGRect vis=CGRectMake(self.contentOffset.x, self.contentOffset.y, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds));
    NSArray *subviews=self.subviews;
    int count=subviews.count;
    for (int i=0; i<count; i++) {
        UIView *v=subviews[i];
        CGRect rect=v.frame;
        if (!CGRectIntersectsRect(vis, rect)) {
            NSString *uuid=v.uuid;
            if ([uuid isEqualToString:str]) {
                [v removeFromSuperview];
                view=v;
                break;
            }
        }
    }
    return view;
}

-(UIView*)newViewWithIdentifier:(NSString*)str{
    if (str==nil) {
        str=NSStringFromCString(defaultIdentifier);
    }
    UIView *view=[[UIView alloc] initWithFrame:CGRectZero];
    view.uuid=str;
    return view;
}

-(void)hideInvisibleView{
    CGRect vis=CGRectMake(self.contentOffset.x, self.contentOffset.y, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds));
    NSArray *subviews=self.subviews;
    int count=subviews.count;
    for (int i=0; i<count; i++) {
        UIView *v=subviews[i];
        NSString *uuid=v.uuid;
        if (uuid) {
            CGRect rect=v.frame;
            if (!CGRectIntersectsRect(vis, rect)) {
                v.hidden=YES;
            }
        }
    }
}

-(void)loadVisibleView{
    CGRect vis=CGRectMake(self.contentOffset.x, self.contentOffset.y, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds));
    int count=self.arrRect.count;
    for (int i=0; i<count; i++) {
        NSString *rectStr=self.arrRect[i];
        CGRect rect=CGRectFromString(rectStr);
        if (CGRectIntersectsRect(vis, rect)) {
            UIView *view=[self loadView:i];
            view.frame=rect;
            view.hidden=NO;
        }
    }
}

-(UIView*)loadView:(int)index{
    UIView *view=nil;
    for (UIView *v in self.subviews) {
        NSString *uuid=v.uuid;
        if (uuid) {
            if (v.tag==index) {
                view=v;
                break;
            }
        }
    }
    if (!view) {
        view=[self.dataSource containerView:self viewAtIndex:index];
        [self addSubview:view];
        view.tag=index;
    }
    return view;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self hideInvisibleView];
    [self loadVisibleView];
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (self.pagingEnabled) {
        CGRect vis=CGRectMake(self.contentOffset.x, self.contentOffset.y, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds));
        int count=self.arrRect.count;
        for (int i=0; i<count; i++) {
            NSString *rectStr=self.arrRect[i];
            CGRect rect=CGRectFromString(rectStr);
            if (CGRectIntersectsRect(vis, rect)) {
                UIView *view=[self loadView:i];
                if ([self.dataSource respondsToSelector:@selector(containerView:didScrollTo:atIndex:)]) {
                    [self.dataSource containerView:self didScrollTo:view atIndex:i];
                }
            }
        }
    }
}
//- (BOOL)touchesShouldBegin:(NSSet *)touches withEvent:(UIEvent *)event inContentView:(UIView *)view{
//    if ([view isKindOfClass:[UIControl class]]) {
//        return YES;
//    }
//    NSInteger index=[self.subviews indexOfObject:view];
//    if (index!=NSNotFound) {
//        if ([self.dataSource respondsToSelector:@selector(containerView:didSelectView:atIndex:)]) {
//            return NO;
//        }
//    }
//    return YES;
//}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    UIView *view=nil;
    UITouch *touch=touches.anyObject;
    CGPoint pt=[touch locationInView:self];
    for (UIView *v in self.subviews) {
        NSString *uuid=v.uuid;
        if (uuid) {
            if (v.hidden==NO) {
                CGRect rect=v.frame;
                if (CGRectContainsPoint(rect, pt)) {
                    view=v;
                }
            }
        }
    }
    if (view) {
        if ([self.dataSource respondsToSelector:@selector(containerView:didSelectView:atIndex:)]) {
            [self.dataSource containerView:self didSelectView:view atIndex:view.tag];
        }
    }
}
@end
